package com.geeklei.media.ui.controller;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.geeklei.media.ui.IUserEventListener;
import com.geeklei.media.ui.R;
import com.geeklei.media.ui.utils.DKTimeFormatter;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import tv.danmaku.ijk.media.player.AbstractMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class MediaController extends RelativeLayout {
    public static final String TAG = "MediaController";
    private OnClickListener mClickListener = new OnClickListener() {
        public void onClick(View view) {
            if (view == MediaController.this.mPauseButton) {
                if (mVideoPause) {
                    if (mIUserEventListener != null && mIUserEventListener.canPlay()) {
                        MediaController.this.togglePause();
                    }
                } else {
                    MediaController.this.togglePause();
                }
            } else if (view == MediaController.this.mNextButton && mIUserEventListener != null) {
                MediaController.this.mIUserEventListener.playNext();
            }
        }
    };

    private TextView mCurrentTime;
    private TextView mEndTime;
    private boolean mIsSeeking = false;
    private ImageView mNextButton;
    private OnPauseOrStartListener mOnPauseOrStartListener;
    private ImageView mPauseButton;
    private AbstractMediaPlayer mPlayer;
    private SeekBar mSeekBar;

    private Float mCurrentSpeed = 1.0f;
    private com.geeklei.media.ui.IUserEventListener mIUserEventListener;


    public boolean mVideoPause = false;

    //seekBar的所有逻辑都在这里处理-----------------------------------------------------------------start
    /**
     * <br/>Author: tony(110618445@qq.com)
     * <br/>Date: 2016/6/23 0023
     * <br/>Time: 11:15
     * <br/>Description:
     * <br/>这个类中只处理主动拖拽seekBar的交互逻辑
     */

    private MyHandler handler = new MyHandler(this);
    int progress;

    /**
     * 用于拖拽时获取已记录的时间点
     *
     * @return
     */
    public int getProgress() {
        return progress;
    }

    public void startProgressTimer() {
        if (seekBarTimer == null) {
            seekBarTimer = new Timer();
            seekBarTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mPlayer == null) {
                        return;
                    }
                    if (mPlayer.isPlaying() && mSeekBar.isPressed() == false) {
                        handler.sendEmptyMessage(0);
                    }
                }
            }, 100, 1000);
        }
    }

    public void cancelProgressTimer() {
        Log.i("destr----", getClass().getName());
        if (seekBarTimer != null) {
            seekBarTimer.cancel();
            seekBarTimer = null;
        }
        if (seekBarTimer != null) {
            seekBarTimer.cancel();
            seekBarTimer = null;
        }
    }


    class SeekBarChangeEvent implements OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            //系统bug,回调时,系统回传的progress有时会为0,这里特殊处理下,如果progress为初始化的值,
            //什么都不做return,下面的回调同理
            if (progress == 0) {
                return;
            }
            // 原本是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()
            MediaController.this.progress = (int) (progress * mPlayer.getCurrentPosition() / seekBar.getMax());
            mCurrentTime.setText(DKTimeFormatter.getInstance().stringForTime(MediaController.this.progress));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (progress == 0) {
                return;
            }
            mPlayer.seekTo(progress);

        }
    }

    private Timer seekBarTimer;


    public void updateProgress(int currentTime, int endTime) {
        //secondaryProgress = 100 * mPlayer.getTotalBuffering() / mPlayer.getDuration();
//        Log.d(TAG, "buffering:" + mPlayer.getBufferPercentage());
//        mSeekBar.setSecondaryProgress((int) mPlayer.getTotalBuffering());
        mEndTime.setText(DKTimeFormatter.getInstance().stringForTime(endTime));
        mCurrentTime.setText(DKTimeFormatter.getInstance().stringForTime(currentTime));
    }

    /**
     * 滑动改变seekBar相关的runnable
     */
    private Runnable mSeekEndRunner = new Runnable() {
        public void run() {
            if (mPlayer != null) {
                if (MediaController.this.progress > 0) {
                    mPlayer.seekTo(MediaController.this.progress);
                }
            }
        }
    };
    //seekBar的所有逻辑都在这里处理-----------------------------------------------------------------end

    public interface OnPauseOrStartListener {
        void onPauseEnd();

        void onPauseStart();
    }


    public MediaController(Context context, AttributeSet attributeSet, int i) {
        super(context, attributeSet, i);
        init();
    }

    public MediaController(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }

    public MediaController(Context context) {
        super(context);
        init();
    }

    private void init() {
        setFocusable(true);
        setFocusableInTouchMode(true);
    }

    public void attachPlayer(AbstractMediaPlayer mediaPlayerControl, com.geeklei.media.ui.IUserEventListener userEventListener) {
        this.mPlayer = mediaPlayerControl;
        this.mIUserEventListener = userEventListener;
    }


    public int getDuration() {
        if (this.mPlayer != null) {
            return (int) this.mPlayer.getDuration();
        }
        return 0;
    }

    public void onFinishInflate() {
        super.onFinishInflate();
        this.mPauseButton = (ImageView) findViewById(R.id.pause);
        this.mPauseButton.setOnClickListener(this.mClickListener);
        this.mNextButton = (ImageView) findViewById(R.id.next);
        this.mNextButton.setOnClickListener(this.mClickListener);
        this.mSeekBar = (SeekBar) findViewById(R.id.mediacontroller_progress);
        this.mSeekBar.setOnSeekBarChangeListener(new SeekBarChangeEvent());
        this.mEndTime = (TextView) findViewById(R.id.time);
        this.mCurrentTime = (TextView) findViewById(R.id.time_current);
        startProgressTimer();
    }

    public void togglePause() {
        if (this.mPlayer != null) {
            if (this.mVideoPause) {
                start();
                if (this.mOnPauseOrStartListener != null) {
                    this.mOnPauseOrStartListener.onPauseStart();
                    return;
                }
                return;
            }
            pause();
            if (this.mOnPauseOrStartListener != null) {
                this.mOnPauseOrStartListener.onPauseEnd();
            }
        }
    }

    public void setNextButtonVisible(boolean z) {
        this.mNextButton.setVisibility(z ? VISIBLE : GONE);
    }

    public void setSeekBarEnable(boolean isEnable) {
        this.mSeekBar.setEnabled(isEnable);
    }

    public void pause() {
        if (this.mPlayer != null) {
            this.mVideoPause = true;
            this.mPlayer.pause();
            updatePlayingState();
        }
    }

    public void start() {
        if (this.mPlayer != null) {
            Log.d(TAG, "start");
            this.mVideoPause = false;
            this.mPlayer.start();
            updatePlayingState();
        }
    }

    private void updatePlayingState() {
        if (this.mVideoPause) {
            this.mPauseButton.setImageResource(R.drawable.vp_mc_play);
        } else {
            this.mPauseButton.setImageResource(R.drawable.vp_mc_pause);
        }
    }

    public void seekStepStart(int currentPosition) {
        if (this.mPlayer != null) {
            if (!this.mIsSeeking) {
                checkPlayingState();
            }
            this.mIsSeeking = true;
            sendSeekMessage(currentPosition);
        }
    }

    public void seekStepEnd() {
        if (this.mPlayer != null) {
            this.mIsSeeking = false;
            this.mSeekEndRunner.run();
        }
    }


    private void sendSeekMessage(int currentPosition) {
        if (currentPosition <= this.mPlayer.getDuration()) {
            this.progress = currentPosition;
        }
    }

    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    private void checkPlayingState() {
        if (this.mPlayer == null || this.mPlayer.isPlaying()) {
            this.mVideoPause = false;
        } else {
            this.mVideoPause = true;
        }
    }

    protected void onVisibilityChanged(View view, int i) {
        super.onVisibilityChanged(view, i);
        if (view == this) {
            if (i == VISIBLE) {
                checkPlayingState();
                updatePlayingState();
            } else {
            }
//            if (this.mPlayer != null && mCurrentSpeed != null) {
//                this.mPlayer.setSpeed(mCurrentSpeed);
//            }
//            if (this.mVisibilityMonitor != null) {
//                this.mVisibilityMonitor.onVisibilityChanged(i == 0);
//            }
        }
    }

    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    public void setOnPauseOrStartListener(OnPauseOrStartListener onPauseOrStartListener) {
        this.mOnPauseOrStartListener = onPauseOrStartListener;
    }


    /**
     * 设置速度
     *
     * @param speed 速度值
     */
    public void updateSppedStatus(float speed) {
        mCurrentSpeed = speed;
    }

    /**
     * 用于GestureSeek访问MediaPlayer获取视频状态
     *
     * @return
     */
    public AbstractMediaPlayer getPlayer() {
        if (mPlayer != null) {
            return mPlayer;
        }
        return null;
    }

    /**
     * 只用来处理seekBar相关的定时刷新!
     */
    class MyHandler extends Handler {
        private WeakReference<MediaController> weakReference;

        public MyHandler(MediaController mediaController) {
            weakReference = new WeakReference<>(mediaController);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MediaController mediaController = weakReference.get();
            int position = (int) mPlayer.getCurrentPosition();
            int duration = (int) mPlayer.getDuration();

            if (duration > 0 && position > 0) {
                //pos=100 * mPlayer.getCurrentPosition() / mPlayer.getDuration();
                long pos = mediaController.mSeekBar.getMax() * position / duration;
                mediaController.mSeekBar.setProgress((int) pos);
                //ui刷新当前时间,总时间
                mediaController.updateProgress(position, duration);
            }
        }
    }
}
